import java.util.*;

public class Solution1345 {

    public int minJumps(int[] arr) {
        Map<Integer, List<Integer>> map=new HashMap<>();
        for (int i=0;i<arr.length;i++){
            List<Integer> list=map.getOrDefault(arr[i],new ArrayList<>());
            list.add(i);
            map.put(arr[i],list);
        }
        Set<Integer> set=new HashSet<>();
        int[] visit=new int[arr.length];
        Arrays.fill(visit,Integer.MAX_VALUE);
        visit[0]=0;
        Queue<int[]> queue=new LinkedList<>();
        queue.add(new int[]{0,0});
        while (!queue.isEmpty()){
            int[] t=queue.poll();
            if (t[0]==arr.length-1){
                return t[1];
            }
            if (t[0]>0 && visit[t[0]-1]==Integer.MAX_VALUE){
                queue.offer(new int[]{t[0]-1,t[1]+1});
                visit[t[0]-1]=t[1]+1;
            }
            if (visit[t[0]+1]==Integer.MAX_VALUE){
                queue.offer(new int[]{t[0]+1,t[1]+1});
                visit[t[0]+1]=t[1]+1;
            }
            if (!set.contains(arr[t[0]])) {
                List<Integer> list = map.getOrDefault(arr[t[0]], new ArrayList<>());
                for (Integer integer : list) {
                    if (visit[integer] == Integer.MAX_VALUE) {
                        set.add(arr[t[0]]);
                        queue.offer(new int[]{integer,t[1]+1});
                        visit[integer]=t[1]+1;
                    }
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1345().minJumps(new int[]{100,-23,-23,404,100,23,23,23,3,404}));
    }
}
